from typing import List

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from database.manager import DbManager
from database.models import Booking as BookingModel
from database.schemas.booking import BookingResponse, BookingCreate
from security import check_token

router = APIRouter()

db_manager = DbManager()


@router.get("/", response_model=List[BookingResponse])
def get_bookings(db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    bookings = db.query(BookingModel).all()
    return bookings


@router.get("/{booking_id}", response_model=BookingResponse)
def get_booking(booking_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    booking = db.query(BookingModel).filter(BookingModel.id == booking_id).first()
    if booking is None:
        raise HTTPException(status_code=404, detail="Booking not found")
    return booking


@router.get("/user/{user_id}", response_model=List[BookingResponse])
def get_user_bookings(user_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    bookings = db.query(BookingModel).filter(BookingModel.user_id == user_id).all()
    if not bookings:
        raise HTTPException(status_code=404, detail="No bookings found for this user")
    return bookings


@router.post("/", response_model=BookingResponse)
def add_booking(booking: BookingCreate, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    db_booking = BookingModel(**booking.dict())
    db.add(db_booking)
    db.commit()
    db.refresh(db_booking)
    return db_booking


@router.delete("/{booking_id}", response_model=BookingResponse)
def delete_booking(booking_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    booking = db.query(BookingModel).filter(BookingModel.id == booking_id).first()
    if booking is None:
        raise HTTPException(status_code=404, detail="Booking not found")
    db.delete(booking)
    db.commit()
    return {"detail": "Booking deleted"}


@router.put("/{booking_id}", response_model=BookingResponse)
def edit_booking(booking_id: int, booking: BookingCreate, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    db_booking = db.query(BookingModel).filter(BookingModel.id == booking_id).first()
    if db_booking is None:
        raise HTTPException(status_code=404, detail="Booking not found")
    db_booking.user_id = booking.user_id
    db_booking.tour_id = booking.tour_id
    db_booking.date = booking.date
    db.commit()
    db.refresh(db_booking)
    return db_booking